import { Request, Response, NextFunction, RequestHandler } from 'express'
import multer, { FileFilterCallback } from 'multer'
import { Jimp } from 'jimp'
import { imageResizer } from './file.service'

export const fileFilter = (fileTypes: Array<string>) => {
  return (
    req: Request,
    file: Express.Multer.File,
    callback: FileFilterCallback
  ) => {
    const isAllowed = fileTypes.includes(file.mimetype)
    if (isAllowed) {
      callback(null, true)
    } else {
      callback(new Error('Invalid file type'))
    }
  }
}

const fileUpload = multer({
  dest: 'uploads/'
})

export const fileInterceptor: RequestHandler = fileUpload.single('file')

export const fileProcessor = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { path, mimetype } = req.file

  if (!mimetype.startsWith('image/')) return next()

  try {
    const image = await Jimp.read(path)
    const { width, height } = image
    req.fileMetaData = { width, height }

    imageResizer(image, req.file)
  } catch (error) {
    next(error)
  }

  next()
}
